package scala

import scala.io.Source

object Demo23Student {
  def main(args: Array[String]): Unit = {

    /**
      * 统计班级的平均年龄
      *
      */

    //1、读取学生数据
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList

    //2、取出班级和年龄
    val clazzAndAge: List[(String, Int)] = students.map((student: String) => {
      val split: Array[String] = student.split(",")
      val clazz: String = split(4)
      val age: Int = split(2).toInt
      (clazz, age)
    })

    //3、将同一个班级分到同一个组内
    val group: Map[String, List[(String, Int)]] = clazzAndAge.groupBy((kv: (String, Int)) => kv._1)


    //4、统计班级的平均年龄

    val clazzAvgAge: Map[String, Double] = group.map((kv: (String, List[(String, Int)])) => {
      val clazz: String = kv._1

      val clazzs: List[(String, Int)] = kv._2

      //取出年龄
      val ages: List[Int] = clazzs.map((i: (String, Int)) => i._2)

      //计算平均年龄
      val avgAge: Double = ages.sum / ages.length.toDouble

      (clazz, avgAge)
    })

    clazzAvgAge.foreach(println)

  }

}
